#include "coin.h"
#include <QDebug>

//Coin::Coin(QWidget *parent)
//    : QPushButton{parent}
//{

//}

Coin::Coin(QString fileName)
{
    QPixmap pix;
    bool ret = pix.load(fileName);
    if(!ret)
    {
        qDebug() << "路径加载失败";
        return;
    }
    this->setFixedSize(pix.width(), pix.height());
    this->setStyleSheet("QPushButton{border:0px}");
    this->setIcon(pix);
    this->setIconSize(QSize(pix.width(), pix.height()));

    //初始化定时器
    timer1 = new QTimer(this);
    timer2 = new QTimer(this);

    //监听正面翻转
    connect(timer1, &QTimer::timeout, [=](){
        QPixmap pix;
        QString str = QString(":/res/Coin000%1.png").arg(this->min++);
        pix.load(str);

        this->setFixedSize(pix.width(), pix.height());
        this->setStyleSheet("QPushButton{border:0px}");
        this->setIcon(pix);
        this->setIconSize(QSize(pix.width(), pix.height()));

        //如果翻完了 将min置1 定时器停止
        if(this->min > this->max)
        {
            this->min = 1;
            timer1->stop();
            this->isAnimation = false;
        }
    });
    //监听反面翻转
    connect(timer2, &QTimer::timeout, [=](){
        QPixmap pix;
        QString str = QString(":/res/Coin000%1.png").arg(this->max--);
        pix.load(str);

        this->setFixedSize(pix.width(), pix.height());
        this->setStyleSheet("QPushButton{border:0px}");
        this->setIcon(pix);
        this->setIconSize(QSize(pix.width(), pix.height()));

        //如果翻完了 将max置8 定时器停止
        if(this->max < this->min)
        {
            this->max = 8;
            timer2->stop();
            this->isAnimation = false;
        }
    });
}
void Coin::changeFlag()
{
    if(this->flag)
    {
        this->isAnimation = true;
        //开始正面翻转
        timer1->start(30);
        //标志置反
        this->flag = false;
    }
    else
    {
        this->isAnimation = true;
        //开始反面翻转
        timer2->start(30);
        //标志置正
        this->flag = true;
    }
}
//重写按钮按下事件（在未完成动画时拦截按下  或者是游戏胜利后不让继续点击金币）
void Coin::mousePressEvent(QMouseEvent *e)
{
    if(this->isAnimation || this->isWin)
    {
        return;
    }
    else
    {
        return QPushButton::mousePressEvent(e);
    }
}
